package com.ruoyi.bluebera.task;



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bluebera.domain.BizOrders;
import com.ruoyi.bluebera.domain.BizTxScanLogs;
import com.ruoyi.bluebera.service.IBizOrdersService;
import com.ruoyi.bluebera.service.IBizTxScanLogsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Component("BERATask")

public class BeraChainTask {

    private static final String API_URL_TEMPLATE = "https://api.etherscan.io/v2/api?chainid=%s&module=transaction&action=gettxreceiptstatus&txhash=%s&apikey=%s";
    private static final RestTemplate restTemplate = createRestTemplateWithTimeout(10000, 10000);
    private static final String apiKey = "K487N1EU8R4PIJIF5X6DGB98ICVHASFYPD";
    private static final String beraChainId = "80094";


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IBizOrdersService bizOrdersService;
    @Autowired
    private IBizTxScanLogsService bizTxScanLogsService;

    @Transactional
    public void checkBERAStatus(){
        // 1. get all preprocessing
        BizOrders bizOrders = new BizOrders();
        bizOrders.setTxStatus("Processing");
        bizOrders.setNetwork(beraChainId);
        List<BizOrders> list = bizOrdersService.selectBizOrdersList(bizOrders);
        // 2. process according token
        for (BizOrders order : list) {

            Date date = order.getScanLastChecked();
            LocalDateTime scanLastChecked = (date != null)
                    ? LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault())
                    : LocalDateTime.now();
            String txStatus = checkTxStatus(order.getNetwork(), order.getTxHash(), apiKey, scanLastChecked);
            // change order status and txstatus
            order.setStatus(txStatus);
            if("Completed".equalsIgnoreCase(txStatus)) {
                order.setTxStatus(txStatus);
                //logger.warn("bera updated order={}", order);
                // add content to tx log
                BizTxScanLogs bizTxScanLogs = new BizTxScanLogs();
                /*
                amount DECIMAL(36, 18) default NULL COMMENT '数量',
                bluebera_amount DECIMAL(36, 18) default NULL COMMENT '兑换的bluebera数量',
                rate_to_bluebera DECIMAL(18, 8) default NULL COMMENT '兑换bluebera汇率',
                 */
                // todo -- need tx info
                bizTxScanLogs.setOrderId(order.getId());
                //bizTxScanLogs.setPaymentAddress(order.getWalletAddress());
                bizTxScanLogs.setTxHash(order.getTxHash());
                bizTxScanLogs.setTokenSymbol(order.getTokenSymbol());
                bizTxScanLogs.setNetwork(order.getNetwork());

                //bizTxScanLogs.setAmount(order.getAmountPaid());
                bizTxScanLogs.setBlueberaAmount(order.getBlueberaAmount());
                //bizTxScanLogs.setRateToBluebera(order.getRateToBluebera());
                bizTxScanLogs.setScannedAt(new Date());
                bizTxScanLogsService.insertBizTxScanLogs(bizTxScanLogs);
            }
            bizOrdersService.updateBizOrders(order);
        }

    }
    /**
     * 检查交易状态。
     *
     * @param chainId          区块链网络 ID（如 80094）
     * @param txHash           交易哈希
     * @param apiKey           API Key
     * @param scanLastChecked  上次检查时间
     * @return                 返回 "Completed" 或 "Pending"
     *
     * {
     *    "status":"1",
     *    "message":"OK",
     *    "result":{
     *       "status":"1"
     *    }
     * }
     * 其中
     * The status field returns 0 for failed transactions and 1 for successful transactions.
     */
    public static String checkTxStatus(String chainId, String txHash, String apiKey, LocalDateTime scanLastChecked) {
        String url = String.format(API_URL_TEMPLATE, chainId, txHash, apiKey);
        long pastSeconds = 2*60*1000;  // bera

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                JSONObject json = JSON.parseObject(response.getBody());

                String status = json.getString("status");
                JSONObject result = json.getJSONObject("result");
                String txStatus = result.getString("status"); // 0=失败，1=成功

                System.out.println("API Status: " + status);
                System.out.println("Tx Result Status: " + txStatus);

                // 判断：API 响应正常，且交易状态为成功
                if ("1".equals(status) && "1".equals(txStatus)) {
                    long secondsPassed = Duration.between(scanLastChecked, LocalDateTime.now()).getSeconds();
                    if (secondsPassed > pastSeconds) {
                        return "Completed";
                    }
                }
            } else {
                System.err.println("HTTP error: " + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Processing";
    }

    private static RestTemplate createRestTemplateWithTimeout(int connectTimeoutMillis, int readTimeoutMillis) {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(connectTimeoutMillis);
        factory.setReadTimeout(readTimeoutMillis);
        return new RestTemplate(factory);
    }

    // 示例调用
    public static void main(String[] args) {
        String chainId = "80094";   // bera
        String txHash = "0x44451707c526be07699b60d5ac00fc416a31a0799940eb3063e4ffc05fee2af7";
        String apiKey = "K487N1EU8R4PIJIF5X6DGB98ICVHASFYPD";

        LocalDateTime lastChecked = LocalDateTime.now().minusSeconds(120); // 模拟上次扫描时间
        long waitSeconds = 60; // 至少间隔 60 秒

        String status = checkTxStatus(chainId, txHash, apiKey, lastChecked);
        System.out.println("Final Status: " + status);
    }
}

